<template>
  <div class="module module02 bpm-task">
    <a-tabs v-model:activeKey="activeKey" class="bpm-task-tabs" @change="handleTabChange">
      <template #rightExtra>
        <div class="refresh more-icon">
          <div>
            <Pagination
              v-model:current="queryParam.pageNo"
              v-model:page-size="queryParam.pageSize"
              size="small"
              simple
              :total="total"
              @change="handlePageChange"
            />
          </div>
          <a-button size="small" type="text">
            <sync-outlined :spin="loading" @click="refreshList()" />
          </a-button>
          <a-button size="small" type="text">
            <template v-slot:icon>
              <router-link
                :to="taskManagePath"
                style="display: flex; align-items: center; justify-items: center; width: 100%; height: 100%"
              >
                <avic-icon svg="MoreOutlined" />
              </router-link>
            </template>
          </a-button>
        </div>
      </template>

      <!-- 我的待办 -->
      <a-tab-pane key="todo" class="bpm-task-pane" :force-render="true">
        <template v-slot:tab>
          <!-- <a-badge :count="todoTotal" :offset="[12, 8]"> -->
          <span>
            我的待办
            <a-tag>{{ todoTotal }}</a-tag>
          </span>
          <!-- </a-badge> -->
        </template>
        <div class="module-in">
          <div class="backlog table-wrapper">
            <AvicTable
              ref="avicTable"
              :data-source="todoList"
              :columns="columns"
              :show-table-setting="false"
              :pagination="false"
              :loading="loading"
              :row-key="(record) => record.dbid"
              :bordered="false"
              auto-header-height
              :stripe="false"
              resizable="true"
              size="default"
              :row-height="40"
              @change="handleTableChange"
            >
              <template #bodyCell="{ column, text, record }">
                <template v-if="column.key === 'originalTaskTitle'">
                  <a-tooltip placement="left">
                    <template #title>
                      <span>被拿回</span>
                    </template>
                    <avic-icon
                      v-if="
                        record.sendType == 'dowithdraw' ||
                        record.sendType == 'dowithdrawassignee' ||
                        record.sendType == 'dowithdrawassigneeop'
                      "
                      class="a-icon-style"
                      svg="avic-undo"
                      color="#F06500"
                    />
                  </a-tooltip>
                  <a-tooltip placement="left">
                    <template #title>
                      <span>被退回</span>
                    </template>
                    <avic-icon
                      v-if="
                        record.sendType == 'doretreattoprev' ||
                        record.sendType == 'doretreattoactivity' ||
                        record.sendType == 'doretreattowant' ||
                        record.sendType == 'doretreattodraft'
                      "
                      svg="avic-reply-fill"
                      class="a-icon-style"
                      color="#EE0000"
                    />
                  </a-tooltip>
                  <a-tooltip placement="left">
                    <template #title>
                      <span>被委托</span>
                    </template>
                    <avic-icon v-if="record.workhandType == 's'" class="a-icon-style" svg="avic-entrust" color="#2BCB95" />
                  </a-tooltip>
                  <span :title="record.originalTaskTitle || record.activityalias_">
                    <a href="javascript:;" class="table-detail-link" @click.stop="toFlowDetail(record)">
                      {{ record.originalTaskTitle || record.activityalias_ }}
                    </a>
                  </span>
                </template>
                <template v-else-if="column.key === 'priority'">
                  <a-tag v-if="text == 2" color="red" text="特急">
                    特急
                    <template #icon>
                      <avic-icon svg="avic-time-fill" />
                    </template>
                  </a-tag>
                  <a-tag v-if="text == 1" color="orange" text="紧急">
                    紧急
                    <template #icon>
                      <avic-icon svg="avic-time-fill" />
                    </template>
                  </a-tag>
                  <a-tag v-if="text == 0" color="blue" text="一般">
                    一般
                    <template #icon>
                      <avic-icon svg="avic-time-fill" />
                    </template>
                  </a-tag>
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-button type="link" class="inner-btn" @click="batchHandleTodo(record)">办理</a-button>
                </template>
              </template>
            </AvicTable>
          </div>
        </div>
      </a-tab-pane>

      <!-- 我的待阅 -->
      <a-tab-pane key="read" class="bpm-task-pane" :force-render="true">
        <template v-slot:tab>
          <!-- <a-badge :count="readTotal" :offset="[12, 8]"> -->
          <span>
            我的待阅
            <a-tag>{{ readTotal }}</a-tag>
          </span>
          <!-- </a-badge> -->
        </template>
        <div class="module-in bpm-task-content">
          <div class="backlog table-wrapper">
            <AvicTable
              ref="avicTable"
              :columns="columns"
              :data-source="readList"
              :show-table-setting="false"
              :pagination="false"
              :loading="loading"
              :row-key="(record) => record.dbid"
              :bordered="false"
              auto-header-height
              :stripe="false"
              resizable="true"
              size="default"
              :row-height="40"
              @change="handleTableChange"
            >
              <template #bodyCell="{ column, text, record }">
                <template v-if="column.key === 'originalTaskTitle'">
                  <a-tooltip placement="left">
                    <template #title>
                      <span>被拿回</span>
                    </template>
                    <avic-icon
                      v-if="
                        record.sendType == 'dowithdraw' ||
                        record.sendType == 'dowithdrawassignee' ||
                        record.sendType == 'dowithdrawassigneeop'
                      "
                      class="a-icon-style"
                      svg="avic-undo"
                      color="#F06500"
                    />
                  </a-tooltip>
                  <a-tooltip placement="left">
                    <template #title>
                      <span>被退回</span>
                    </template>
                    <avic-icon
                      v-if="
                        record.sendType == 'doretreattoprev' ||
                        record.sendType == 'doretreattoactivity' ||
                        record.sendType == 'doretreattowant' ||
                        record.sendType == 'doretreattodraft'
                      "
                      svg="avic-reply-fill"
                      class="a-icon-style"
                      color="#EE0000"
                    />
                  </a-tooltip>
                  <a-tooltip placement="left">
                    <template #title>
                      <span>被委托</span>
                    </template>
                    <avic-icon v-if="record.workhandType == 's'" class="a-icon-style" svg="avic-entrust" color="#2BCB95" />
                  </a-tooltip>
                  <span :title="record.originalTaskTitle || record.activityalias_">
                    <a href="javascript:;" class="table-detail-link" @click.stop="toFlowDetail(record)">
                      {{ record.originalTaskTitle || record.activityalias_ }}
                    </a>
                  </span>
                </template>
                <template v-else-if="column.key === 'priority'">
                  <a-tag v-if="text == 2" color="red" text="特急">
                    特急
                    <template #icon>
                      <avic-icon svg="avic-time-fill" />
                    </template>
                  </a-tag>
                  <a-tag v-if="text == 1" color="orange" text="紧急">
                    紧急
                    <template #icon>
                      <avic-icon svg="avic-time-fill" />
                    </template>
                  </a-tag>
                  <a-tag v-if="text == 0" color="blue" text="一般">
                    一般
                    <template #icon>
                      <avic-icon svg="avic-time-fill" />
                    </template>
                  </a-tag>
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-button type="link" class="inner-btn" @click="handleToRead(record)">已阅</a-button>
                </template>
              </template>
            </AvicTable>
          </div>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script lang="ts">
export default defineComponent({
  name: 'MyTask'
});
</script>

<script lang="ts" setup>
import { batchHandle, getBatchHandleInfo } from '@/api/avic/bpm/BpmTaskApi'; // 引入模块API
import { listBpmTaskListByPage, saveBpmFinishReader } from '@/api/avic/bpm/BpmTaskAndReadApi'; // 获取列表数据
import { Pagination } from 'ant-design-vue';
import bpmUtils from '@/views/avic/bpm/bpmutils/FlowUtils'; // 引入流程相关配置及方法

const columns = ref<any>([
  {
    title: '标题',
    dataIndex: 'originalTaskTitle',
    ellipsis: true,
    minWidth: 240,
    key: 'originalTaskTitle'
  },
  {
    title: '流程名称',
    dataIndex: 'processDefName',
    align: 'left',
    ellipsis: true,
    width: 160
  },
  {
    title: '紧急程度',
    dataIndex: 'priority',
    align: 'left',
    sorter: true,
    width: 120,
    key: 'priority'
  },
  {
    title: '节点',
    dataIndex: 'activityalias_',
    align: 'left',
    ellipsis: true,
    width: 120
  },
  {
    title: '发送人',
    dataIndex: 'taskSendUser',
    align: 'left',
    ellipsis: true,
    width: 120
  },
  {
    title: '接收时间',
    dataIndex: 'createTime',
    width: 160,
    align: 'left',
    sorter: true,
    customRender: (obj) => {
      if (obj.text) {
        return proxy.$dateFormat(obj.text);
      }
      return '';
    }
  }
  // {
  //   title: '操作',
  //   dataIndex: 'action',
  //   key: 'action',
  //   ellipsis: true,
  //   width: 80,
  //   align: 'left',
  //   fixed: 'right'
  // }
]);
const queryParam = reactive({
  // 请求表格数据参数
  pageNo: 1, // 页数
  pageSize: 8, // 每页条数
  sidx: null, // 排序字段
  sord: null, // 排序方式: desc降序 asc升序
  taskType: '0'
});
const batchHandleParam = reactive({
  // 批量办理请求接口
  entryIds: '',
  executionIds: '',
  taskIds: ''
});
const todoList = ref([]); // 待办数据集合
const todoTotal = ref(0); // 待办总条数
const readList = ref([]); // 待阅数据集合
const readTotal = ref(0); // 待阅总条数
const loading = ref(false); // 表格loading状态
const todoPage = ref(1); // 待办当前浏览页码
const readPage = ref(1); // 待阅当前浏览页码
const activeKey = ref('todo'); // 当前激活tab面板的key
const total = ref(0); // 数据总条数
const { proxy } = getCurrentInstance();
const taskManagePath = '/bpm/bpmtask'; // 静态页面跳转

onMounted(() => {
  // 执行待办查询
  getTodoList();
  // 执行待阅查询
  getReadList();
});
/** 待办数据查询 */
function getTodoList({ notUpdateSession } = { notUpdateSession: false }) {
  loading.value = true;
  queryParam.taskType = '0';
  listBpmTaskListByPage(queryParam, notUpdateSession)
    .then((response: any) => {
      todoList.value = response.data.todoRows;
      todoTotal.value = response.data.todoTotal;
      if (activeKey.value === 'todo') {
        total.value = todoTotal.value;
      }
    })
    .finally(() => {
      loading.value = false;
    })
    .catch(() => {
      todoList.value = [];
      todoTotal.value = 0;
      total.value = 0;
    });
}

function getReadList({ notUpdateSession } = { notUpdateSession: false }) {
  loading.value = true;
  queryParam.taskType = '1';
  listBpmTaskListByPage(queryParam, notUpdateSession)
    .then((response: any) => {
      readList.value = response.data.readRows;
      readTotal.value = response.data.readTotal;
      if (activeKey.value === 'read') {
        total.value = readTotal.value;
      }
    })
    .finally(() => {
      loading.value = false;
    })
    .catch(() => {
      readList.value = [];
      readTotal.value = 0;
      total.value = 0;
    });
}

function getList({ notUpdateSession } = { notUpdateSession: false }) {
  if (activeKey.value === 'todo') {
    getTodoList({ notUpdateSession });
  } else if (activeKey.value === 'read') {
    getReadList({ notUpdateSession });
  }
}

/** 公共分页 */
function handlePageChange(value) {
  queryParam.pageNo = value;
  if (activeKey.value === 'todo') {
    todoPage.value = value;
  } else if (activeKey.value === 'read') {
    readPage.value = value;
  }
  getList();
}
/** 刷新按钮 */
function refreshList(params?: any) {
  getList(params);
}
/** 升序降序 */
function handleTableChange(pagination, _filters, sorter) {
  if (proxy.$objIsNotBlank(sorter.field)) {
    queryParam.sidx = sorter.field;
    queryParam.sord = sorter.order === 'ascend' ? 'asc' : 'desc'; // 排序方式: desc降序 asc升序
  }
  getList();
}
/** 流程跳转 */
function toFlowDetail(row) {
  if (row.processDefName) {
    bpmUtils.executeTask(
      row.processInstance,
      row.executionId,
      row.dbid,
      row.businessId,
      row.formResourceName,
      row.processDefName || row.taskTitle,
      row.taskType,
      '',
      bpmOperatorRefresh,
      '',
      '',
      '',
      row.siteType
    );
  } else {
    /** 非流程待办 */
    let url = row.formResourceName;
    if (url == null || url === '') {
      return;
    }
    if (url.indexOf('?') > 0) {
      url += `&processInstanceId=${row.processInstance}`;
    } else {
      url += `?processInstanceId=${row.processInstance}`;
    }
    url += `&taskId=${row.dbid}`;
    url += `&id=${row.businessId}`;

    let skipUrl = '';
    if (url.indexOf('?') !== -1) {
      const urlStr = url.split('?');
      skipUrl = `${encodeURIComponent(urlStr[0].replace(RegExp('/', 'g'), '_'))}?${urlStr[1]}`;
    } else {
      skipUrl = encodeURIComponent(url.replace(RegExp('/', 'g'), '_'));
    }
    let { base } = proxy.$settings.routerOptions;
    if (base?.endsWith('/')) {
      base = base.substring(0, base.length - 1);
    }
    window.open(`${base || ''}/notFlowTodoDetail/${skipUrl}`, 'NotFlowTodoDetailWin');
    window[`bpmOperatorRefresh${row.processInstance}`] = () => {
      bpmOperatorRefresh();
    };
  }
}
/** 流程跳转刷新 */
function bpmOperatorRefresh() {
  refreshList();
}
/** 待办与待阅切换状态判断 */
function handleTabChange(params: string) {
  if (params === 'todo') {
    total.value = todoTotal.value;
  } else if (params === 'read') {
    total.value = readTotal.value;
  }
}
/** 待办办理 */
function batchHandleTodo(record: any) {
  batchHandleParam.entryIds = record.processInstance;
  batchHandleParam.executionIds = record.executionId;
  batchHandleParam.taskIds = record.dbid;
  proxy.$Modal.confirm({
    title: '确定对数据进行办理吗？',
    content: '提示：只有符合办理前提条件的才会被办理成功',
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      batchHandle(batchHandleParam).then((res: any) => {
        if (res.success) {
          const resultData = res.data;
          const falureCnt = resultData.result[2];
          if (falureCnt > 0) {
            proxy.$message.error('不符合办理条件的待办无法办理！');
          } else {
            getBatchHandlesInfo();
          }
        }
      });
    }
  });
}
/** 待办办理后的回调 */
function getBatchHandlesInfo() {
  getBatchHandleInfo()
    .then((res: any) => {
      if (res.success) {
        proxy.$message.success('数据办理成功！');
        getList();
      }
    })
    .catch((e) => {
      console.error(e, 'err');
    });
}
/** 点击阅后的回调 */
function handleToRead(row) {
  // modal提示是否删除
  proxy.$Modal.confirm({
    title: '确定标记为已阅吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      // 确认删除
      saveFinishReader(row);
    }
  });
}
/** 点击已阅后流程的移除 */
function saveFinishReader(row) {
  const param = {
    dbid: row.dbid,
    entryId: row.processInstance,
    doTask: true
  };
  saveBpmFinishReader(param).then((response: any) => {
    if (response.success) {
      getList();
    }
  });
}
/** 自动刷新 */
function loadData(params?: any) {
  refreshList(params);
}
defineExpose({
  loadData
});
</script>

<style lang="less">
@import '../style/base.less';
</style>
<style lang="less" scoped>
:deep(.ant-tabs-nav) {
  padding: 0 12px;
  margin-bottom: 8px;
  &::before {
    border: 0;
  }
  .ant-tabs-tab {
    margin-right: 8px;
    padding: 12px 0 8px 0;

    &.ant-tabs-tab-active .ant-tabs-tab-btn {
      font-weight: 600;
      text-shadow: none;
    }
  }
  .ant-tag {
    height: 20px;
    margin: 0;
    border-radius: 12px;
    background-color: @border-color-split;
    border: @border-color-split;
  }
  .ant-tabs-tab-active {
    .ant-tag {
      color: #fff;
      background-color: @primary-color;
      border: @primary-color;
    }
  }
}
:deep(.ant-tabs-content) {
  .backlog {
    padding-bottom: 12px;
  }
}
</style>
